/**
 * Created by xxcao on 2017/6/9.
 */

var sql = require('./sqlMapping');
var util = require('../util/util');
var code = require('../util/code');

module.exports = {
    get:function (req, res , next) {
        if (util.isParameterEmpty(req.query.user_id, req.query.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            new Promise(function (resolve) {
               connection.query(sql.board.findPersonInGroup, [req.query.user_id, req.query.board_id], function (err, results) {
                   if (err) {
                       res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, "查询出错"));
                       connection.release();
                   } else {
                       if (results.length > 0) {
                           resolve(results);
                       } else {
                           res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法操作'));
                           connection.release();
                       }
                   }
               });
            }).then(function (results) {
                return new Promise(function (resolve) {
                    var sqlStr = sql.task.findsWithPhaseId;
                    var params = [req.query.board_id, req.query.phase_id];
                    if (util.isParameterEmpty(req.query.phase_id)){
                        sqlStr = sql.task.finds;
                        params = [req.query.board_id];
                    }
                    connection.query(sqlStr, params, function (err, results) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, "查询出错"));
                            connection.release();
                        } else {
                            resolve(results);
                        }
                    });
                });
            }).then(function (results) {
                return new Promise(function (resolve) {
                    //查询任务所附带的问题
                    var sqls = [];
                    var params = [];
                    for (var i = 0; i < results.length; i++) {
                        sqls.push(sql.issue.finds);
                        params.push([results[i].task_id]);
                    }
                    msqlQueries.queries(sqls, params, function(err, result){
                        if(err) {
                            var jsonString = util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '查询任务所附带的问题失败');
                            res.json(jsonString);
                            connection.release();
                        } else {
                            var tasks = [];
                            for (var i = 0; i < results.length; i++) {
                                var task = results[i];
                                task.issues = result[i];
                                tasks.push(task);
                            }
                            res.json(util.toJson(code.OPERATE_SUCCESS, '查询任务成功', tasks));
                            connection.release();
                        }
                    });
                });
            });
        });
    },
    delete:function (req, res, next) {
        if (util.isParameterEmpty(req.body.user_id, req.body.task_id, req.body.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'PUT')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err) {
                throw err;
            }
            new Promise(function (resolve) {
                connection.query(sql.board.findPersonInGroup, [req.body.user_id, req.body.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法删除该任务'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.task.findOne, [req.body.task_id], function (err, results) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除失败'));
                            connection.release();
                        } else {
                            if (results && results.length > 0) {
                                resolve(results[0]);
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '您要删除的任务不存在'));
                                connection.release();
                            }
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                   var task = result;
                   if(task.current_status === 4) {
                       res.json(util.toJson(code.IS_DELETED, '该任务已经被删除'));
                       connection.release();
                   } else {
                       resolve(task)
                   }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var task = result;
                    if(task.creator !== req.body.user_id) {
                        res.json(util.toJson(code.IS_NOT_TO_BE, '您不是该任务的创建者，无法删除'));
                        connection.release();
                    } else {
                        resolve(task)
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var task = result;
                    connection.query(sql.task.deleteOne, [req.body.task_id], function (err, result) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '删除失败'));
                            connection.release();
                        } else {
                            res.json(util.toJson(code.OPERATE_SUCCESS, '删除成功'));
                            // connection.release();
                            resolve(task);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var content = results[index].user_name + "在看板：" + results[index].board_name + "里删除了任务：" + result.task_content;
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if (!util.isParameterEmpty(results[j].client_id)) {
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                });
            });
        });
    },
    receive:function (req, res, next) {//领取任务
        if (util.isParameterEmpty(req.body.user_id, req.body.task_id, req.body.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'PUT')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err) {
                throw err;
            }
            var task = null;
            new Promise(function (resolve) {
                connection.query(sql.board.findPersonInGroup, [req.body.user_id, req.body.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法领取该任务'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.task.findOne, [req.body.task_id], function (err, results) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '领取失败'));
                            connection.release();
                        } else {
                            if (results && results.length > 0) {
                                resolve(results[0]);
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '您要领取的任务不存在'));
                                connection.release();
                            }
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    task = result;
                    if(task.current_status === 2) {
                        res.json(util.toJson(code.IS_TO_BE, '该任务已经被领取'));
                        connection.release();
                    } else if (task.current_status > 2)  {
                        res.json(util.toJson(code.IS_NOT_CAN, '该任务的状态不对，不能被领取'));
                        connection.release();
                    } else if(task.current_status === 1){
                        //此状态可以领取
                        resolve(task);
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardPhases, [req.body.board_id], function (err, results) {
                        if (err === null && results && results.length > 0) {
                            resolve(results[0]);
                        } else {
                            res.json(util.toJson(code.IS_NOT_CAN, '该看板没有阶段，不能被领取'));
                            connection.release();
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var sqlString = null;
                    var param = null;
                    if (util.isParameterEmpty(req.body.user_id)) {
                        sqlString = sql.task.updateWithoutExcutor;
                        param = [req.body.task_id, result.phase_id];
                    } else {
                        sqlString = sql.task.updateWithExcutor;
                        param = [req.body.user_id, req.body.task_id, result.phase_id];
                    }
                    connection.query(sqlString, param, function (err, result) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '领取失败'));
                            connection.release();
                        } else {
                            res.json(util.toJson(code.OPERATE_SUCCESS, '领取成功'));
                            // connection.release();
                            resolve(result);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var content = results[index].user_name + "在看板：" + results[index].board_name + "里领取了任务：" + task.task_content;
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if (!util.isParameterEmpty(results[j].client_id)){
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                });
            });
        });
    },
    create:function (req, res, next) {//创建激活（任何人都可以创建）
        if (util.isParameterEmpty(req.body.user_id, req.body.task_content, req.body.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'POST')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err) {
                throw err;
            }

            new Promise(function (resolve) {
                connection.query(sql.board.findPersonInGroup, [req.body.user_id, req.body.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法创建任务'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.task.findSameName, [req.body.task_content, req.body.board_id], function (err, results) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建任务失败'));
                            connection.release();
                            return;
                        }
                        if (results.length > 0) {
                            res.json(util.toJson(code.EXISTED, '该看板下存在相同名称的任务，请重试'));
                            connection.release();
                        } else {
                            resolve(results);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardPhases, [req.body.board_id], function (err, results) {
                        if (err === null && results && results.length > 0) {
                            resolve(results[0]);
                        } else {
                            res.json(util.toJson(code.IS_NOT_CAN, '该看板没有阶段，任务不能被创建'));
                            connection.release();
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var task_id = util.getUUID();
                    var prarams = [task_id, req.body.board_id, req.body.task_content];
                    if (util.isParameterEmpty(req.body.task_remark)) {//备注
                        prarams.push(null);
                    } else {
                        prarams.push(req.body.task_remark);
                    }
                    prarams.push(req.body.user_id);//创建者
                    if (util.isParameterEmpty(req.body.task_executor)) {//执行者
                        prarams.push(null);
                        prarams.push(null);
                        prarams.push(1);//仅激活
                    } else {
                        prarams.push(req.body.task_executor);
                        prarams.push('now()');
                        prarams.push(2);//激活并指派
                    }
                    if (util.isParameterEmpty(req.body.finish_date)) {//完成时限
                        prarams.push(null);
                    } else {
                        prarams.push(req.body.finish_date);
                    }
                    prarams.push(result.current_phase_id);
                    if (util.isParameterEmpty(req.body.current_attribute_id)) {//属性id
                        prarams.push(null);
                    } else {
                        prarams.push(req.body.current_attribute_id);
                    }
                    connection.query(sql.task.insert, prarams, function (err, result) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '创建失败'));
                            connection.release();
                        } else {
                            resolve(task_id);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var attachments = JSON.parse(req.body.attachments);
                    if (attachments.length > 0) {
                        var sqls = [];
                        var parameters = [];
                        for (var i = 0; i < attachments.length; i++) {
                            sqls.push(sql.task.insertAttachment);
                            parameters.push([result, attachments[i]]);
                        }
                        msqlQueries.queries(sqls, parameters, function(err, result){
                            if(err) {
                                var jsonString = util.toJson(code.CREATE_FAILURE, '创建失败');
                                res.json(jsonString);
                                connection.release();
                            } else {
                                res.json(util.toJson(code.OPERATE_SUCCESS, '创建成功'));
                                // connection.release();
                                resolve(result);
                            }
                        });
                    } else {
                        res.json(util.toJson(code.OPERATE_SUCCESS, '创建成功'));
                        // connection.release();
                        resolve(result);
                    }
                });
            })
                .then(function (result) {
                   return new Promise(function (resolve) {
                     connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var content = results[index].user_name + "在看板" + results[index].board_name + "里创建了任务：" + req.body.task_content;
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if (!util.isParameterEmpty(results[j].client_id)) {
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                   });
            });
        });
    },
    changeStatus:function (req, res, next) {
        if (util.isParameterEmpty(req.body.user_id, req.body.task_id, req.body.board_id, req.body.current_phase_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'PUT')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if (err) {
                throw err;
            }
            var curTask = null;
            new Promise(function (resolve) {
                //判断人属不属于这个看板
                connection.query(sql.board.findPersonInGroup, [req.body.user_id, req.body.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法操作任务'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    //判断任务存不存在
                    connection.query(sql.task.findOne, [req.body.task_id], function (err, results) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '操作任务失败'));
                            connection.release();
                        } else {
                            if (results && results.length > 0) {
                                curTask = results[0];
                                resolve(results[0]);
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '任务不存在'));
                                connection.release();
                            }
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardPhases, [req.body.board_id], function (err, results) {
                        if (err === null && results && results.length > 0) {
                            resolve(results);
                        } else {
                            res.json(util.toJson(code.IS_NOT_CAN, '该看板没有阶段，不能被操作'));
                            connection.release();
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var param = {};
                    param.phases = result;
                    connection.query(sql.board.findMaster, [req.body.user_id, req.body.board_id], function (err, result) {
                        if (result && result.length > 0){
                            param.isMaster = 1;
                        } else {
                            param.isMaster = 0;
                        }
                        resolve(param);
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var phases = result.phases;
                    var cIdx = phases.indexOf(curTask.current_phase_id);
                    var pIdx = phases.indexOf(req.body.current_phase_id);
                    if (pIdx < 0) {
                        res.json(util.toJson(code.PARAMETER_ERROR, '阶段id传的不对'));
                        connection.release();
                        return;
                    }
                    if(result.isMaster === 1) {
                         if (pIdx > cIdx){
                             res.json(util.toJson(code.IS_NOT_CAN, '管理员不能前进看板的状态'));
                             connection.release();
                         } else {
                             resolve(req.body.current_phase_id);
                         }
                    } else {
                        if(pIdx < cIdx) {
                            res.json(util.toJson(code.IS_NOT_CAN, '看板成员不能后退看板的状态'));
                            connection.release();
                        } else {
                            resolve(req.body.current_phase_id);
                        }
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.task.updateCurrentPhase, [result, req.body.task_id], function (err, result) {
                        if (err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '操作看板失败'));
                            connection.release();
                        } else {
                            res.json(util.toJson(code.OPERATE_SUCCESS, '操作看板成功'));
                            // connection.release();
                            resolve(result);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var content = results[index].user_name + "在看板：" + results[index].board_name + "里更新了任务：" + curTask.task_content + "的状态";
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if (!util.isParameterEmpty(results[j].client_id)) {
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                });
            });
        });
    },
    update:function (req, res, next) {
        if (util.isParameterEmpty(req.body.user_id, req.body.task_id, req.body.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'PUT')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if (err) {
                throw err;
            }
            var task = null;
            new Promise(function (resolve) {
                //判断人属不属于这个看板
                connection.query(sql.board.findPersonInGroup, [req.body.user_id, req.body.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法更新任务'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    //判断任务存不存在
                    connection.query(sql.task.findOne, [req.body.task_id], function (err, results) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '更新任务失败'));
                            connection.release();
                        } else {
                            if (results && results.length > 0) {
                                task = results[0];
                                resolve(results[0]);
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '当前任务不存在'));
                                connection.release();
                            }
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findMaster, [req.body.user_id, req.body.board_id], function (err, results) {
                        var isAllowUpdate = false;
                        if (results && results.length > 0){
                           //看板管理员
                            isAllowUpdate = true;
                        } else {
                            if(task.creator === req.body.user_id) {
                               //任务创建者
                                isAllowUpdate = true;
                            } else {
                                res.json(util.toJson(code.IS_NOT_TO_BE, '您不是该任务的创建者或者看板管理员，无法更新任务'));
                                connection.release();
                            }
                        }
                        if (isAllowUpdate) {
                            resolve(result);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    if (!util.isParameterEmpty(req.body.task_content)) {
                        connection.query(sql.task.findSameName, [req.body.task_content, req.body.board_id], function (err, results) {
                            if (err) {
                                res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '更新任务失败'));
                                connection.release();
                                return;
                            }
                            if (results.length > 0) {
                                res.json(util.toJson(code.EXISTED, '该看板下存在相同名称的任务，请重试'));
                                connection.release();
                            } else {
                                resolve();
                            }
                        });
                    } else {
                        resolve();
                    }
                })
            })
                .then(function (result) {
                    return new Promise(function (resolve) {
                        var sqls = [];
                        var params = [];
                        if (!util.isParameterEmpty(req.body.task_content)){
                            sqls.push(sql.task.updateTask);
                            params.push(['task_content', req.body.task_content, req.body.task_id]);
                        }
                        if (!util.isParameterEmpty(req.body.task_remark)){
                            sqls.push(sql.task.updateTask);
                            params.push(['task_remark', req.body.task_remark, req.body.task_id]);
                        }
                        if (!util.isParameterEmpty(req.body.task_executor)){
                            sqls.push(sql.task.updateTask);
                            params.push(['task_executor', req.body.task_executor, req.body.task_id]);

                            sqls.push(sql.task.updateTask);
                            params.push(['current_status', req.body.current_status, req.body.task_id]);

                            sqls.push(sql.task.updateTask);
                            params.push(['active_date', req.body.active_date, req.body.task_id]);
                        }
                        if (!util.isParameterEmpty(req.body.finish_date)){
                            sqls.push(sql.task.updateTask);
                            params.push(['finish_date', req.body.finish_date, req.body.task_id]);
                        }
                        if (!util.isParameterEmpty(req.body.current_attribute_id)){
                            sqls.push(sql.task.updateTask);
                            params.push(['current_attribute_id', req.body.current_attribute_id, req.body.task_id]);
                        }
                        msqlQueries.queries(sqls, params, function(err, result){
                            if(err) {
                                res.json(util.toJson(code.UPDATE_FAILURE, '更新失败'));
                                connection.release();
                            } else {
                                res.json(util.toJson(code.OPERATE_SUCCESS, '更新成功'));
                                // connection.release();
                                resolve(result);
                            }
                        });
                    });
            })
                .then(function (result) {
                    return new Promise(function (resolve) {
                        connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                            if (err) {
                                connection.release();
                            } else {
                                if(results.length > 0) {
                                    var index = 0;
                                    for (var i = 0; i < results.length; i++){
                                        if (results[i].user_id === req.body.user_id){
                                            index = i;
                                            break;
                                        }
                                    }
                                    var content = results[index].user_name + "在看板：" + results[index].board_name + "里更新了任务：" + task.task_content;
                                    var params = [];
                                    var sqls = [];
                                    for (var j = 0; j < results.length; j++) {
                                        if (results[j].user_id !== req.body.user_id) {
                                            if (!util.isParameterEmpty(results[j].client_id)) {
                                                getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                    console.log(data);
                                                },function (err) {
                                                    console.error(err);
                                                });
                                            }
                                        }
                                        //插入动态消息
                                        sqls.push(sql.news.insert);
                                        params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                    }
                                    msqlQueries.queries(sqls, params, function (err, result) {
                                        connection.release();
                                    });
                                }
                                else {
                                    connection.release();
                                }
                            }
                        });
                    });
                });
        });
    },
    addComment:function (req, res, next) {
        var item_id = null;
        if (req.body.type === 1){
            //任务
            item_id  = req.body.task_id;
        } else {
            //问题
            item_id  = req.body.issue_id;
        }
        if (util.isParameterEmpty(req.body.user_id, item_id, req.body.comment_content)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'POST')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err){
                throw err;
            }
            var attachments = JSON.parse(req.body.attachments);
            var tmpIssue = null;
            new Promise(function (resolve) {
                var is_has_attachment = 0;
                if (attachments.length > 0) {
                    is_has_attachment = 1;
                }
                var comment_id = util.getUUID();
                var param = [comment_id, item_id, req.body.comment_content, is_has_attachment, req.body.user_id];
                connection.query(sql.task.insertComment, param, function (err, result) {
                    if(err) {
                        res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '添加批注失败'));
                        connection.release();
                    } else {
                        resolve(comment_id);
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    if (attachments.length > 0) {
                        var sqls = [];
                        var parameters = [];
                        for (var i = 0; i < attachments.length; i++) {
                            sqls.push(sql.task.insertAttachment);
                            parameters.push([result, attachments[i]]);
                        }
                        msqlQueries.queries(sqls, parameters, function(err, result){
                            if(err) {
                                var jsonString = util.toJson(code.CREATE_FAILURE, '添加批注失败');
                                res.json(jsonString);
                                connection.release();
                            } else {
                                res.json(util.toJson(code.OPERATE_SUCCESS, '添加批注成功'));
                                // connection.release();
                                resolve();
                            }
                        });
                    } else {
                        res.json(util.toJson(code.OPERATE_SUCCESS, '添加批注成功'));
                        // connection.release();
                        resolve();
                    }
                });
            })
                .then(function (result) {
                    return new Promise(function (resolve) {
                        if (req.body.type === 1){
                            //任务 req.body.task_id;
                            connection.query(sql.task.findOne, [req.body.task_id], function (err, result) {
                               if (err) {
                                   connection.release();
                               } else {
                                   if(result && result.length > 0){
                                       resolve(result[0]);
                                   } else {
                                       connection.release();
                                   }
                               }
                            });
                        } else {
                            //问题 req.body.issue_id;
                            connection.query(sql.issue.findIssue, [req.body.issue_id], function (err, result) {
                                if (err) {
                                    connection.release();
                                } else {
                                    if(result && result.length > 0){
                                        tmpIssue = result[0];
                                        connection.query(sql.task.findOne, [tmpIssue.task_id], function (err, result) {
                                            if (err) {
                                                connection.release();
                                            } else {
                                                if(result && result.length > 0){
                                                    resolve(result[0]);
                                                } else {
                                                    connection.release();
                                                }
                                            }
                                        });
                                    } else {
                                        connection.release();
                                    }
                                }
                            });
                        }
                    });
                })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var task = result;
                    connection.query(sql.board.findBoardMembersAll, [task.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var conStr = null;
                                if (req.body.type === 1){
                                    conStr = "给任务：" + task.task_content;
                                } else {
                                    conStr = "给问题：" + tmpIssue.issue_content;
                                }
                                var content = results[index].user_name + conStr + '添加了一条批注';
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if (!util.isParameterEmpty(results[j].client_id)) {
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                });
            });
        });
    },
    archive:function (req, res, next) {
        if (util.isParameterEmpty(req.body.user_id, req.body.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'POST')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if (err) {
                throw err;
            }
            var archive_id = null;
            new Promise(function (resolve) {
                connection.query(sql.board.findBoardPhases, [req.body.board_id], function (err, results) {
                    if (err === null && results && results.length > 0) {
                        resolve(results);
                    } else {
                        res.json(util.toJson(code.IS_NOT_CAN, '该看板没有阶段，不能被操作'));
                        connection.release();
                    }
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    var last_phase_id = result[result.length - 1].phase_id;
                    connection.query(sql.task.findsWithPhaseIdOrdered, [req.body.board_id, last_phase_id], function (err, results) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '归档失败'));
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                resolve(results);
                            } else {
                                res.json(util.toJson(code.NOT_EXISTED, '没有归档任务，无法归档'));
                                connection.release();
                            }
                        }
                    });
                });
            })
                .then(function (results) {
                return new Promise(function (resolve) {
                    var startDate = results[0].create_date;
                    var endDate = results[results.length - 1].create_date;
                    archive_id = util.getUUID();
                    var params = [archive_id, req.body.board_id, startDate, endDate, results.length];
                    connection.query(sql.task.insertArchive, params, function (err, result) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '归档失败'));
                            connection.release();
                        } else {
                            resolve(results[0].current_phase_id);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.task.updateArchive, [archive_id, req.body.board_id, result], function (err, result) {
                        if(err) {
                            res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '归档失败'));
                            connection.release();
                        } else {
                            res.json(util.toJson(code.OPERATE_SUCCESS, '归档成功'));
                            // connection.release();
                            resolve(result);
                        }
                    });
                });
            })
                .then(function (result) {
                return new Promise(function (resolve) {
                    connection.query(sql.board.findBoardMembersAll, [req.body.board_id], function (err, results) {
                        if (err) {
                            connection.release();
                        } else {
                            if(results.length > 0) {
                                var index = 0;
                                for (var i = 0; i < results.length; i++){
                                    if (results[i].user_id === req.body.user_id){
                                        index = i;
                                        break;
                                    }
                                }
                                var content = results[index].user_name + "在看板：" + results[index].board_name + "里归档了任务";
                                var params = [];
                                var sqls = [];
                                for (var j = 0; j < results.length; j++) {
                                    if (results[j].user_id !== req.body.user_id) {
                                        if(!util.isParameterEmpty(results[j].client_id)) {
                                            getui.pushMessageToSingle(results[j].client_id, content, content, 0, null).then(function (data) {
                                                console.log(data);
                                            },function (err) {
                                                console.error(err);
                                            });
                                        }
                                    }
                                    //插入动态消息
                                    sqls.push(sql.news.insert);
                                    params.push([util.getUUID(), content, results[j].user_id, 1, results[j].board_id]);
                                }
                                msqlQueries.queries(sqls, params, function (err, result) {
                                    connection.release();
                                });
                            }
                            else {
                                connection.release();
                            }
                        }
                    });
                });
            });
        });
    },
    archives:function (req, res, next) {
       //to do archives
        if (util.isParameterEmpty(req.query.user_id, req.query.board_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err) {
                throw err;
            }
            new Promise(function (resolve) {
                //判断人属不属于这个看板
                connection.query(sql.board.findPersonInGroup, [req.query.user_id, req.query.board_id], function (err, result) {
                    if (result.length > 0) {
                        resolve(result);
                    } else {
                        res.json(util.toJson(code.NOT_EXISTED, '您不属于当前看板，无法获取归档'));
                        connection.release();
                    }
                });
            }).then(function (result) {
                connection.query(sql.task.findArchives, [req.query.board_id], function (err, results) {
                    if (err) {
                        res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '获取归档失败'));
                        connection.release();
                    } else {
                        res.json(util.toJson(code.OPERATE_SUCCESS, '获取归档成功', results));
                        connection.release();
                    }
                });
            });
        });
    },
    archiveTasks:function (req, res, next) {
       //to do archive tasks
        if (util.isParameterEmpty(req.query.user_id, req.query.archive_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req, 'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.connection(function (err, connection) {
            if(err) {
                throw err;
            }
            connection.query(sql.task.findArchiveTasks, [req.query.archive_id], function (err, results) {
                if (err) {
                    res.json(util.toJson(code.DATABASE_SQL_EXCUTE_ERROR, '获取归档的任务失败'));
                    connection.release();
                } else {
                    res.json(util.toJson(code.OPERATE_SUCCESS, '获取归档的任务成功', results));
                    connection.release();
                }
            });
        });
    }
};